﻿using System.Linq;
using CardPlay.Model.ActionModel;

namespace CardPlay.Model.GameModel.Actions
{
    public class DealOutTableauAction : GameAction
    {
        private ComplexAction _action;

        public DealOutTableauAction(CardGame cardGame, PartLocation location) : base(cardGame, location)
        {
            TargetPattern = CardGame.AnyTableau;
        }

        public string TargetPattern { get; set; }

        protected override void OnExecute()
        {
            Action.Execute();
        }

        protected override void OnReverse()
        {
            Action.Reverse();
        }

        private IAction Action
        {
            get
            {
                if (_action == null)
                {
                    _action = new ComplexAction();

                    var location = Location;

                    foreach (var to in CardGame.PilesNamed(TargetPattern).Select(pile => new PartLocation(pile.Name, pile.Count)))
                    {
                        _action.Add(new FlipCardAction(CardGame, location));
                        _action.Add(new MoveCardAction(CardGame, location, to));

                        if (--location.Index < 0)
                            break;
                    }
                }

                return _action;
            }
        }
    }
}
